package com.liusuai.yixian.config;

import com.alibaba.fastjson.JSONObject;
import com.liusuai.yixian.domain.ResultBean;
import com.liusuai.yixian.login.UserBean;
import com.liusuai.yixian.login.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Autowired //自动连接到UserService Bean
    private UserMapper userMapper;

    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);


    /**
     * 在请求被处理之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        logger.info("preHandle :"+request.getRequestURL().toString());
        // 检查每个到来的请求对应的session域中是否有登录标识
        HttpSession session = request.getSession(false);

        ResultBean resultBean = checkSession(session);
        if (resultBean.isSuccess()) {
            return true;
        } else {
            responseOutWithJson(response, resultBean);
            return false;
        }

    }

    public ResultBean checkSession(HttpSession session) {
        if (session == null) {
            //未登录
            logger.info("您还未登录");
            return getResult(300, "您还未登录", false);
        }

        Object userId = session.getAttribute("userId");

        if (null == userId || !(userId instanceof String)) {
            // session过期
            logger.info("session过期");
            return getResult(300, "session过期，您可能长时间未操作", false);
        } else {
            //session没有过期
            UserBean userBean = userMapper.selectUserById((String) userId);
            if (userBean == null) {
                logger.info("账号异常");
                return getResult(300, "账号异常", false);
            } else {
                if (userBean.getLoginId().equals(session.getId())) {
                    //验证通过
                    logger.info("当前用户已登录，cookie为： " + session.getId());
                    ResultBean result = getResult(100, "session验证成功，当前用户已登录", true);
                    result.setData(userBean);
                    return result;
                } else {
                    //验证失败

                    return getResult(300, "session过期,您可能在其他地方已经登录", false);
                }
            }

        }
    }


    protected ResultBean getResult(int code, String msg, boolean isSuc) {
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(code);
        resultBean.setMsg(msg);
        resultBean.setSuccess(isSuc);
        return resultBean;

    }

    /**
     * 以JSON格式输出
     *
     * @param response
     */
    protected void responseOutWithJson(HttpServletResponse response,
                                       ResultBean resultBean) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(resultBean);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(json);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


}
